package com.ovopark.organize.server.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ovopark.device.common.util.LogUtil;
import com.ovopark.organize.common.base.BaseResult;
import com.ovopark.organize.server.common.support.LocalStorageUtils;
import com.ovopark.organize.server.model.entity.*;
import com.ovopark.organize.server.model.query.FranchiseesAddressQuery;
import com.ovopark.organize.server.model.query.FranchiseesRegistrationQuery;
import com.ovopark.organize.server.model.vo.*;
import com.ovopark.organize.server.service.*;
import com.ovopark.organize.server.util.*;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 线索跟进
 */
@RestController
@RequestMapping("/franchiseesRegistration")
public class FranchiseesRegistrationController {
    Logger logger = LoggerFactory.getLogger(FranchiseesRegistrationController.class);
    @Resource
    private FranchiseesRegistrationService franchiseesRegistrationService;
    @Resource
    private FranchiseesRegistrationFieldService franchiseesRegistrationFieldService;
    @Resource
    private FranchiseesRegistrationFollowService franchiseesRegistrationFollowService;
    @Resource
    private FranchiseesRegistrationAddressService franchiseesRegistrationAddressService;

    @Resource
    private FranchiseesRegistrationRecycleService franchiseesRegistrationRecycleService;

    @Resource
    private FranchiseeContractService franchiseeContractService;
    @Resource
    private LogsService logsService;
    @Resource
    private UserService usersService;
    @Resource
    private FranchiseesRegistrationPlanService franchiseesRegistrationPlanService;

    @Resource
    private FranchiseesRegistrationLogService franchiseesRegistrationLogService;


    /**
     * 取 自定义字段
     *
     * @param groupId
     * @return
     */
    @GetMapping("/getFranchiseesRegistrationModuleByGroupId")
    public BaseResult getFranchiseesRegistrationModuleByGroupId(@RequestParam(value = "groupId", required = false) Integer groupId) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        Locale locale = LocalStorageUtils.getStorageInfo().getLocale();

        if (curGroupId != null) {
            groupId = curGroupId;
        }
        if (userId == null || groupId == null) {
            return BaseResult.invalidToken();
        }
        List<FranchiseesRegistrationModuleVo> list = franchiseesRegistrationFieldService.getFranchiseesRegistrationModuleByGroupId(groupId,locale);
        return BaseResult.success(list);
    }


    @GetMapping("/getFranchiseesRegistrationModuleByGroupIdApp")
    public BaseResult getFranchiseesRegistrationModuleByGroupIdApp(@RequestParam(value = "groupId") Integer groupId) {
        Locale locale = Locale.CHINA;
        List<FranchiseesRegistrationModuleVo> list = franchiseesRegistrationFieldService.getFranchiseesRegistrationModuleByGroupId(groupId,locale);
        return BaseResult.success(list);
    }


    /**
     * 新增 线索
     *
     * @return
     */
    @PostMapping("/saveFranchiseesRegistration")
    public BaseResult saveFranchiseesRegistration(@RequestBody FranchiseesRegistrationSaveVo vo) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer groupId = LocalStorageUtils.getStorageInfo().getGroupId();
        String remoteIp = LocalStorageUtils.getStorageInfo().getRemoteIp();
        String platform = LocalStorageUtils.getStorageInfo().getUserPlatform();
        if (groupId != null) {
            vo.setGroupId(groupId);
        }
        if (userId == null || vo.getGroupId() == null) {
            return BaseResult.invalidToken();
        }
        // 手机号 要校验
        if (StringUtil.isNotBlank(vo.getMobilePhone())) {
            List<FranchiseesRegistration> franchiseesRegistrations = franchiseesRegistrationService.getFranchiseesMobilePhone(vo.getId(), vo.getMobilePhone(), vo.getGroupId());
            if (CollectionUtil.isNotEmpty(franchiseesRegistrations)) {
                return BaseResult.error("400", "手机号码已存在");
            }
        }
        franchiseesRegistrationService.saveOrUpdateVo(vo, userId,remoteIp,platform);
        return BaseResult.success();
    }


    /**
     * 保存用户门店首页菜单
     *
     * @return
     */
    @PostMapping("/saveFranchiseesRegistrationApp")
    public BaseResult saveFranchiseesRegistrationApp(@RequestBody FranchiseesRegistrationSaveVo vo) {

        if (vo.getUserId() == null || vo.getGroupId() == null) {
            return BaseResult.invalidToken();
        }
        // 手机号 要校验
        if (StringUtil.isNotBlank(vo.getMobilePhone())) {
            List<FranchiseesRegistration> franchiseesRegistrations = franchiseesRegistrationService.getFranchiseesMobilePhone(vo.getId(), vo.getMobilePhone(), vo.getGroupId());
            if (CollectionUtil.isNotEmpty(franchiseesRegistrations)) {
                return BaseResult.error("400", "手机号码已存在");
            }
        }
        franchiseesRegistrationService.saveOrUpdateVo(vo, vo.getUserId(),"127.0.0.1","app");
        return BaseResult.success();
    }


    /**
     * 获取 固定列表
     *
     * @param
     * @param
     * @param
     * @return
     */
    @PostMapping("/getFranchiseesRegistrationByGroupId")
    public BaseResult getFranchiseesRegistrationByGroupId(@RequestBody FranchiseesRegistrationQuery query) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (curGroupId != null) {
            query.setGroupId(curGroupId);
        }
        if (userId == null || query.getGroupId() == null) {
            return BaseResult.invalidToken();
        }
        Map<String, Object> result = new HashMap<>();
        result.put("total", 0);
        result.put("data", null);

        if(query.getRecycle() ==null){
            query.setRecycle(0);
        }

        List<String> followTypes = new ArrayList<>();
        if(query.getRecycle() ==1){
            query.setFollowType(3);
        }else if(query.getFollowType() ==null) {
            followTypes.add("0");
            followTypes.add("1");
            followTypes.add("2");
            followTypes.add("4");
        }
        if(StringUtils.isNotEmpty(query.getFollowTypes())){
            if(query.getRecycle() ==1){
                query.setFollowTypes(null);
            }else {
                followTypes = Arrays.asList(query.getFollowTypes().split(","));
            }
        }


         if(query.getFilterJoin() && query.getRecycle() !=1){
            if(CollectionUtil.isNotEmpty(followTypes)){
                //去掉加盟状态
                String joinType = "4";
                if(followTypes.contains(joinType)){
                    followTypes.remove(joinType);
                }
            }else {
                followTypes.add("0");
                followTypes.add("1");
                followTypes.add("2");
                followTypes.add("4");
            }
        }

        if(CollectionUtil.isNotEmpty(followTypes)){
            query.setFollowTypes("("+StringUtils.join(followTypes,",")+")");
        }

        if(StringUtils.isNotEmpty(query.getRecycleReasonIds())){
            query.setRecycleReasonIds("("+query.getRecycleReasonIds()+")");
        }

        IPage<FranchiseesRegistrationVo> list = franchiseesRegistrationService.getFranchiseesRegistrationByGroupId(query);
        if (CollectionUtil.isNotEmpty(list.getRecords())) {
            result.put("total", list.getTotal());
            result.put("data", list.getRecords());
        }
        return BaseResult.success(result);
    }


    /**
     * 获取 所有线索 的 姓名 手机号 列表
     *
     * @param
     * @return
     */

    @GetMapping("/getFranchiseesRegistrationList")
    public BaseResult getFranchiseesRegistrationList(@RequestParam(value = "groupId", required = false) Integer groupId) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (curGroupId != null) {
            groupId = curGroupId;
        }
        if (userId == null || groupId == null) {
            return BaseResult.invalidToken();
        }

        List<SimpleStringStringVo> simpleVoList = franchiseesRegistrationService.getSimpleFranchisees(groupId);

        return BaseResult.success(simpleVoList);
    }

    /**
     * 获取线索详情
     * @param registrationId
     * @param isApp
     * @return
     */

    @GetMapping("/getFranchiseesRegistrationById")
    public BaseResult getFranchiseesRegistrationById(@RequestParam(value = "registrationId") Integer registrationId,
                                                     @RequestParam(value = "isApp", defaultValue = "false") Boolean isApp) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null ) {
            return BaseResult.invalidToken();
        }
        FranchiseesRegistrationVo contentVo = franchiseesRegistrationService.getFranchiseesRegistrationById(registrationId, isApp,curGroupId);

        return BaseResult.success(contentVo);
    }

    @GetMapping("/getFranchiseesRegistrationByIdApp")
    public BaseResult getFranchiseesRegistrationByIdApp(@RequestParam(value = "registrationId") Integer registrationId,
                                                     @RequestParam(value = "isApp", defaultValue = "false") Boolean isApp,
                                                     @RequestParam(value = "groupId") Integer  groupId) {
        if (groupId == null) {
            return BaseResult.invalidToken();
        }
        FranchiseesRegistrationVo contentVo = franchiseesRegistrationService.getFranchiseesRegistrationById(registrationId, isApp,groupId);

        return BaseResult.success(contentVo);
    }


    /**
     * 线索 删除 需要 放到回收站，删除只是把线索放入回收站，回收站删除才是真的删除
     */

    @GetMapping("/deletedFranchiseesRegistrationById")
    public BaseResult deletedFranchiseesRegistrationById(@RequestParam(value = "registrationId") Integer registrationId, @RequestParam(value = "deleted", required = false) Integer deleted) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null || curGroupId == null) {
            return BaseResult.invalidToken();
        }
        FranchiseesRegistration registration = franchiseesRegistrationService.findFranchiseesRegistrationById(registrationId);
        if(curGroupId !=null && registration !=null && registration.getGroupId().intValue() != curGroupId){
          return BaseResult.noPrivilege();
        }
        if(registration !=null){
            String remoteIp = LocalStorageUtils.getStorageInfo().getRemoteIp();
            String platform = LocalStorageUtils.getStorageInfo().getUserPlatform();
            franchiseesRegistrationService.deletedFranchiseesRegistrationById(registrationId, deleted, userId,remoteIp,platform);

        }

        return BaseResult.success();
    }



    @PostMapping("/deletedFranchiseesRegistration")
    public BaseResult deletedFranchiseesRegistration(@RequestBody List<Integer> registrationIds) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null  || CollectionUtil.isEmpty(registrationIds)) {
            return BaseResult.paramError();
        }
        for(Integer registrationId : registrationIds){
            FranchiseesRegistration registration = franchiseesRegistrationService.findFranchiseesRegistrationById(registrationId);
            if(curGroupId !=null && registration !=null && registration.getGroupId().intValue() != curGroupId){
                return BaseResult.noPrivilege();
            }
            if(registration !=null){
                String remoteIp = LocalStorageUtils.getStorageInfo().getRemoteIp();
                String platform = LocalStorageUtils.getStorageInfo().getUserPlatform();
                franchiseesRegistrationService.deletedFranchiseesRegistrationById(registrationId, 1, userId,remoteIp,platform);

            }

        }


        return BaseResult.success();
    }



    /**
     * 获取 放入回收站 原因
     */

    @GetMapping("/getRecycleByGroupId")
    public BaseResult getRecycleByGroupId(@RequestParam(value = "groupId") Integer groupId) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if(curGroupId !=null){
            groupId = curGroupId;
        }
        List<SimpleVo> vos = franchiseesRegistrationRecycleService.getRecycleByGroupId(groupId);
        return BaseResult.success(vos);
    }



    /**
     * 线索放入回收站
     */
    @PostMapping("/recycleByRegistrationId")
    public BaseResult recycleByRegistrationId(@RequestBody FranchiseesRegistrationRecycleVo param) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null || curGroupId == null) {
            return BaseResult.invalidToken();
        }
        if(CollectionUtil.isEmpty(param.getRegistrationIds())){
            return BaseResult.paramError();
        }
        if(curGroupId !=null){
            param.setGroupId(curGroupId);
        }


        //4: 放入回收站 跟进人：清空该线索的跟进人 跟进状态：变为已删除 最后跟进人：最近一次跟进记录的创建人
        //删除人：谁进行的线索删除操作 删除原因：删除时选择的删除原因 删除时间：删除操作的时间
        //跟进记录：不变 跟进计划：状态（未开始/已逾期）都变成已取消，取消原因：删除线索（默认不可更改）


        String remoteIp = LocalStorageUtils.getStorageInfo().getRemoteIp();
        String platform = LocalStorageUtils.getStorageInfo().getUserPlatform();


        List<FranchiseesRegistration> franchiseesRegistration = franchiseesRegistrationService.getFranchiseesByFollowUser(param.getGroupId(),param.getRegistrationIds());
        if(CollectionUtil.isNotEmpty(franchiseesRegistration)){
            List<Integer> ids = franchiseesRegistration.stream().map(FranchiseesRegistration::getId).collect(Collectors.toList());
            Map<Integer,FranchiseesRegistrationFollow> finalFollowUserMap = franchiseesRegistrationFollowService.getFinalFollowUserByRegistrationId(param.getGroupId(),ids);

            List<Integer> finalFollowUserNull = new ArrayList<>();
            List<Integer> followUserNull = new ArrayList<>();
            for(FranchiseesRegistration registration : franchiseesRegistration){
                // 未分配类型
                FranchiseesRegistrationFollow follow = finalFollowUserMap.get(registration.getId());
                if(follow !=null){
                    registration.setFinalFollowUser(follow.getCreateId());
                    followUserNull.add(follow.getCreateId());
                }else {
                    finalFollowUserNull.add(registration.getId());
                }
                registration.setFollowUser(null);
                registration.setFollowType(FranchiseesRegistration.FLOW_TYPE_RECYCLE);
                franchiseesRegistrationService.saveOrUpdateBean(registration);
           //     ids.add(registration.getId());
            }

            if(CollectionUtil.isNotEmpty(followUserNull)){
                franchiseesRegistrationService.updateFollowUser(userId,param.getGroupId(),followUserNull,null,FranchiseesRegistration.FLOW_TYPE_RECYCLE,false,true,null,null,false,"operation.recycleByRegistration.description",remoteIp,platform);
            }
            if(CollectionUtil.isNotEmpty(finalFollowUserNull)){
                franchiseesRegistrationService.updateFollowUser(userId,param.getGroupId(),finalFollowUserNull,null,FranchiseesRegistration.FLOW_TYPE_RECYCLE,false,true,null,null,true,"operation.recycleByRegistration.description",remoteIp,platform);
            }
            franchiseesRegistrationRecycleService.recycleByRegistrationId(param,userId);
            // 所有 跟进记录 状态更新为 已取消 原因为 删除学员
            String followUpPlanReason = "删除学员";
            franchiseesRegistrationPlanService.updateFollowUpPlanStatusByRegistrationId(param.getGroupId(),ids,userId,FranchiseesRegistrationFollow.FOLLOW_UP_STATUS_CANCEL,followUpPlanReason);

        }

        return BaseResult.success();
    }

    /**
     * 线索恢复
     * @param
     * @return
     */
    @PostMapping("/recoveryRegistration")
    public BaseResult recoveryRegistration(@RequestBody FranchiseesRegistrationRecycleVo recycleVo) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null || curGroupId == null) {
            return BaseResult.invalidToken();
        }
        if(CollectionUtil.isEmpty(recycleVo.getRegistrationIds())){
            return BaseResult.paramError();
        }
        if(curGroupId !=null){
            recycleVo.setGroupId(curGroupId);
        }

        //5：恢复线索 跟进人：为空 跟进状态：待分配 最后跟进人：最近一次跟进记录的创建人
        //最后跟进时间：拿最新一次跟进记录的跟进时间 下次跟进时间：-

        List<FranchiseesRegistration> franchiseesRegistration = franchiseesRegistrationService.getFranchiseesByFollowUser(recycleVo.getGroupId(),recycleVo.getRegistrationIds());
        if(CollectionUtil.isNotEmpty(franchiseesRegistration)){
           // List<Integer> ids = new ArrayList<>();
            List<Integer> ids = franchiseesRegistration.stream().map(FranchiseesRegistration::getId).collect(Collectors.toList());
            Map<Integer,FranchiseesRegistrationFollow> finalFollowUserMap = franchiseesRegistrationFollowService.getFinalFollowUserByRegistrationId(recycleVo.getGroupId(),ids);
            String parameters = "";
            for(FranchiseesRegistration registration : franchiseesRegistration){
                FranchiseesRegistrationFollow follow = finalFollowUserMap.get(registration.getId());
                if(follow !=null){
                    registration.setFinalFollowUser(follow.getCreateId());
                    registration.setFinalFollowTime(follow.getFollowTime());
                }
                // 未分配类型
                registration.setFollowType(FranchiseesRegistration.FLOW_TYPE_UNDISTRIBUTED);
                ids.add(registration.getId());
                registration.setFollowUser(null);
                franchiseesRegistrationService.saveOrUpdateBean(registration);
                parameters = registration.getName()+registration.getMobilePhone();
            }
            franchiseesRegistrationRecycleService.recoveryRegistrationById(ids,userId);
            franchiseesRegistrationService.cleanFollowUser(ids);
            Users users = usersService.getUsersById(userId);
            String description = "恢复线索";
            String remoteIp = LocalStorageUtils.getStorageInfo().getRemoteIp();
            String platform = LocalStorageUtils.getStorageInfo().getUserPlatform();
            logsService.saveLogsByRemoteIp("recoveryRegistration",users, JSONObject.toJSONString(recycleVo),remoteIp,platform,users.getUserName()+"操作："+description,"operation.recoveryRegistration.description",users.getShowName()+","+parameters);
        }

        return BaseResult.success();
    }



    /**
     * --------------------------------------------------------跟进记录
     */


    /**
     * 新增 跟进记录
     */
    @PostMapping("/saveRegistrationFollow")
    public BaseResult saveRegistrationFollow(@RequestBody FranchiseesRegistrationFollowVo vo) throws ParseException, IOException {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer groupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (groupId != null) {
            vo.setGroupId(groupId);
        }
        if (userId == null || vo.getGroupId() == null) {
            return BaseResult.invalidToken();
        }
        if (vo.getCreateId() == null) {
            vo.setCreateId(userId);
            vo.setCreateTime(new Date());
        }
        // 跟进计划 校验
        FranchiseesRegistration franchiseesRegistration = franchiseesRegistrationService.findFranchiseesRegistrationById(vo.getFranchiseesRegistrationId());
        if(franchiseesRegistration !=null){
            if(vo.getId() !=null && vo.getFollowUpPlan() !=null  && vo.getFollowUpPlan().intValue() == 0 && vo.getOldFollowUpPlan() != null && vo.getOldFollowUpPlan().intValue() == 1){
                List<FranchiseesRegistrationFollow> followList = franchiseesRegistrationFollowService.getRegistrationFollowsByPlanId(vo.getFranchiseesRegistrationId(),vo.getId());
                if(CollectionUtil.isNotEmpty(followList)){
                    return BaseResult.error("400", "一个跟进计划不能同时生成多条已完成的跟进记录！");
                }
            }
            FranchiseesRegistrationFollowVo   followVo = franchiseesRegistrationFollowService.saveNewFollowvo(vo);
            return BaseResult.success(followVo);
        }else {
            return BaseResult.error("400", "线索不存在！");
        }


      /*  if (franchiseesRegistration != null) {
            //一个跟进计划不能同时生成多条已完成的跟进记录    跟进计划  是未完成状态  跟进记录已完成状态下
            if (vo.getId() != null) {
                FranchiseesRegistrationFollow oldVo = franchiseesRegistrationFollowService.getFollowById(vo.getId());
                if (oldVo != null && oldVo.getFollowUpPlanStatus().intValue() == 1 && vo.getFollowUpPlan().intValue() == 0 && vo.getOldFollowUpPlan() != null && vo.getOldFollowUpPlan().intValue() == 1) {
                    return BaseResult.error("400", "一个跟进计划不能同时生成多条已完成的跟进记录！");
                }
            }
        }else {
            return BaseResult.error("400", "线索不存在！");
        }
        FranchiseesRegistrationFollowVo followVo = franchiseesRegistrationFollowService.saveFollowvo(vo);
         return BaseResult.success(followVo);
        */


    }



    /**
     * 删除 跟进记录
     *
     * @param id
     * @return
     */

    @GetMapping("/deleteRegistrationFollow")
    public BaseResult deleteRegistrationFollow(@RequestParam(value = "id") Integer id,@RequestParam(value = "followUpPlan",required = false)  Integer followUpPlan) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer groupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null || followUpPlan == null) {
            return BaseResult.invalidToken();
        }

        Boolean isDelete = true;
        if(followUpPlan !=null && followUpPlan.intValue() == 1){
            // 删除 跟进计划
            isDelete =  franchiseesRegistrationPlanService.deletePlanById(id,groupId);
        }else {
            isDelete = franchiseesRegistrationFollowService.deleteNewFollowById(id,groupId);
        }

        if(!isDelete){
            // 没有权限
            return BaseResult.noPrivilege();
        }
      /*  FranchiseesRegistrationFollow follow = franchiseesRegistrationFollowService.getFollowById(id);
        if (follow != null && (groupId != null && follow.getGroupId().intValue() == groupId)) {
            franchiseesRegistrationFollowService.deleteFollowById(id);
        }*/


        return BaseResult.success();
    }



    /**
     * 获取 跟进记录
     * @param pageSize
     * @param pageNumber
     * @param registrationId
     * @return
     */

    @GetMapping("/getRegistrationFollowByRegistrationId")
    public BaseResult getRegistrationFollowByRegistrationId(@RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                                            @RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                                            @RequestParam(value = "registrationId") Integer registrationId,
                                                            @RequestParam(value = "followUpPlan" ,required = false) Integer followUpPlan,
                                                            @RequestParam(value = "followUpPlanStatus" ,required = false) Integer followUpPlanStatus) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        Map<String, Object> result = new HashMap<>();
        result.put("total", 0);
        result.put("data", null);

        Page<FranchiseesRegistrationFollow> page = new Page<>(pageNumber, pageSize);
        IPage<FranchiseesRegistrationFollow> list = franchiseesRegistrationFollowService.getRegistrationFollowByRegistrationId(page, registrationId,followUpPlan,followUpPlanStatus);
        if (CollectionUtil.isNotEmpty(list.getRecords())) {
            result.put("total", list.getTotal());
            result.put("data", list.getRecords());
        }
        return BaseResult.success(result);
    }

    @GetMapping("/getRegistrationFollows")
    public BaseResult getRegistrationFollows(@RequestParam(value = "registrationId") Integer registrationId) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        Map<String, Object> result = new HashMap<>();
        // 跟进记录
        List<FranchiseesRegistrationFollow> followUplist = franchiseesRegistrationFollowService.getRegistrationFollows(registrationId,0,null);
        result.put("followUpRecords",followUplist);

        List<FranchiseesRegistrationPlan> followUpPlanlist = franchiseesRegistrationPlanService.getRegistrationPlan(registrationId,null);
        //跟进计划
        List<FranchiseesRegistrationPlan> followUpPlans = new ArrayList<>();
        //取消跟进列表
        List<FranchiseesRegistrationPlan> cancelList = new ArrayList<>();

        if(CollectionUtil.isNotEmpty(followUpPlanlist)){
            for (FranchiseesRegistrationPlan follow:followUpPlanlist ) {
                Integer followUpPlanStatus = follow.getFollowUpPlanStatus();
                if(followUpPlanStatus == FranchiseesRegistrationFollow.FOLLOW_UP_STATUS_CANCEL){
                    cancelList.add(follow);
                }else {
                    followUpPlans.add(follow);
                }

            }
        }

       /* List<FranchiseesRegistrationFollow> followUpPlanlist = franchiseesRegistrationFollowService.getRegistrationFollows(registrationId,1,null);
        //跟进计划
        List<FranchiseesRegistrationFollow> followUpPlans = new ArrayList<>();
        //取消跟进列表
        List<FranchiseesRegistrationFollow> cancelList = new ArrayList<>();

        if(CollectionUtil.isNotEmpty(followUpPlanlist)){
            for (FranchiseesRegistrationFollow follow:followUpPlanlist ) {
                Integer followUpPlanStatus = follow.getFollowUpPlanStatus();
                if(followUpPlanStatus == FranchiseesRegistrationFollow.FOLLOW_UP_STATUS_CANCEL){
                    cancelList.add(follow);
                }else {
                    followUpPlans.add(follow);
                }

            }
        }*/

        result.put("followUpPlan",followUpPlans);
        result.put("cancelList",cancelList);

        return BaseResult.success(result);
    }

    /**
     * 线索分配人员 批量  assignPersonnel
     */

    @PostMapping("/updateAssignPersonnel")
    public BaseResult updateAssignPersonnel(@RequestBody BatchIdsVo vo) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer groupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (groupId != null) {
            vo.setGroupId(groupId);
        }
        if (userId == null || vo.getGroupId() == null) {
            return BaseResult.invalidToken();
        }

        String remoteIp = LocalStorageUtils.getStorageInfo().getRemoteIp();
        String platform = LocalStorageUtils.getStorageInfo().getUserPlatform();

        if (CollectionUtil.isNotEmpty(vo.getIds())) {
            if (vo.getUserId() != null) {
                List<String> franchiseesRegistrationsList = new ArrayList<>();
                if (!vo.getCover()) {
                    // 校验
                    List<FranchiseesRegistration> franchiseesRegistrations = franchiseesRegistrationService.getFranchiseesByFollowUser(vo.getGroupId(), vo.getIds());
                    if (CollectionUtil.isNotEmpty(franchiseesRegistrations)) {
                        franchiseesRegistrationsList = franchiseesRegistrations.stream().map(FranchiseesRegistration::getName).collect(Collectors.toList());
                    }
                }
                if (CollectionUtil.isEmpty(franchiseesRegistrationsList)) {
                    franchiseesRegistrationService.updateFollowUser(userId,vo.getGroupId(), vo.getIds(), vo.getUserId(), 1,true,false,null,null,false,"operation.updateAssignPersonnel.description",remoteIp,platform);
                } else {
                    return BaseResult.success(franchiseesRegistrationsList);
                }
            } else {
                String type = "operation.updateAssignPersonnel.description";
                if(vo.getIds().size() == 1){
                    type = "operation.updateGiveUp.description";
                }
                // 清空
                franchiseesRegistrationService.updateFollowUser(userId,vo.getGroupId(), vo.getIds(), null, 0,false,true,null,null,false,type,remoteIp,platform);
            }
            logger.info("getAssignPersonnel==" + userId + "groupId:" + groupId + "data:" + JSONObject.toJSONString(vo));
        }

        return BaseResult.success();
    }



    /**
     * 线索分配人员 单个
     */
    @PostMapping("/updateAssignOnePersonnel")
    public BaseResult updateAssignOnePersonnel(@RequestBody Map<String,Object> param ) {
        Integer registrationId = Integer.valueOf(param.get("registrationId").toString()) ;
         Integer userId = (Integer) param.get("userId");
        Integer groupId = null ;
        if(param.get("groupId") !=null ){
            groupId = (Integer) param.get("groupId");
        }
        Integer curUserId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (curGroupId != null) {
            groupId = curGroupId;
        }
        if (curUserId == null ||groupId == null) {
            return BaseResult.invalidToken();
        }
        String remoteIp = LocalStorageUtils.getStorageInfo().getRemoteIp();
        String platform = LocalStorageUtils.getStorageInfo().getUserPlatform();


        List<Integer> ids = new ArrayList<>();
        ids.add(registrationId);
        franchiseesRegistrationService.updateFollowUser(curUserId,groupId, ids, userId, 1,true,false,null,null,false,"operation.updateAssignOnePersonnel.description",remoteIp,platform);


        return BaseResult.success();
    }
    /**
     * 放弃 线索
     */
    @GetMapping("/updateGiveUp")
    public BaseResult updateGiveUp(@RequestParam("groupId") Integer groupId, @RequestParam("registrationId")  Integer registrationId) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curgroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (curgroupId != null) {
            groupId = curgroupId;
        }
        if (userId == null || groupId == null) {
            return BaseResult.invalidToken();
        }

        if (registrationId !=null) {
            List<Integer> ids = new ArrayList<>();
            ids.add(registrationId);
              // 清空
            String remoteIp = LocalStorageUtils.getStorageInfo().getRemoteIp();
            String platform = LocalStorageUtils.getStorageInfo().getUserPlatform();

            franchiseesRegistrationService.updateFollowUser(userId,groupId, ids, null, 0,false,true,null,null,false,"operation.updateGiveUp.description",remoteIp,platform);
            logger.info("getAssignPersonnel==" + userId + "groupId:" + groupId + "data:" + JSONObject.toJSONString(registrationId));
        }

        return BaseResult.success();
    }



    /**
     * 加盟商 选址-----------------------
     */

    @PostMapping("/saveOrUpdateFranchiseesAddress")
    public BaseResult saveOrUpdateFranchiseesAddress(@RequestBody FranchiseesRegistrationAddress vo) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (curGroupId != null) {
            vo.setGroupId(curGroupId);
        }
        if (vo.getId() == null) {
            vo.setCreateId(userId);
            vo.setCreateTime(new Date());
        }

        FranchiseesRegistrationAddress address = franchiseesRegistrationAddressService.saveOrUpdateFranchiseesAddress(vo);
        return BaseResult.success(address);
    }

    /**
     * 加盟商 选址
     *
     * @param
     * @param
     * @param
     * @return
     */

    @PostMapping("/getFranchiseesAddress")
    public BaseResult getFranchiseesAddress(@RequestBody FranchiseesAddressQuery query) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        Map<String, Object> result = new HashMap<>();
        result.put("total", 0);
        result.put("data", null);
        Integer pageSize = query.getPageSize();
        Integer pageNumber = query.getPageNumber();
        Integer groupId = query.getGroupId();
        if (curGroupId != null) {
            groupId = curGroupId;
        }
        Page<FranchiseesRegistrationAddress> page = new Page<>(pageNumber, pageSize);
        IPage<FranchiseesRegistrationAddressVo> list = franchiseesRegistrationAddressService.getFranchiseesAddressPage(page, groupId, query);
        if (CollectionUtil.isNotEmpty(list.getRecords())) {
            result.put("total", list.getTotal());
            result.put("data", list.getRecords());
        }
        return BaseResult.success(result);
    }


    /**
     * 加盟商 选址 删除
     *
     * @param
     * @param
     * @param
     * @return
     */

    @GetMapping("/deleteFranchiseesAddress")
    public BaseResult deleteFranchiseesAddress(@RequestParam(value = "id") Integer id) {

        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        FranchiseesRegistrationAddress address = franchiseesRegistrationAddressService.getAddressById(id);
        if (curGroupId != null) {
            if (address != null && address.getGroupId() != null && address.getGroupId().intValue() != curGroupId) {
                return BaseResult.noPrivilege();
            }
        }
        franchiseesRegistrationAddressService.deleteAddressById(id);
        logger.info("deleteFranchiseesAddress==" + userId + "data:" + JSONObject.toJSONString(address));
        return BaseResult.success();
    }


    @PostMapping("/batchDeleteFranchiseesAddress")
    public BaseResult batchDeleteFranchiseesAddress(@RequestBody List<Integer> ids) {

        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (CollectionUtil.isNotEmpty(ids)) {
            List<FranchiseesRegistrationAddress> address = franchiseesRegistrationAddressService.getAddressByIds(curGroupId, ids);
            if (CollectionUtil.isNotEmpty(address)) {
                List<Integer> idList = address.stream().map(FranchiseesRegistrationAddress::getId).collect(Collectors.toList());
                franchiseesRegistrationAddressService.deleteAddressByIdList(idList);
                logger.info("batchFranchiseesAddress==" + userId + "data:" + JSONObject.toJSONString(idList));
            }
        }
        return BaseResult.success();
    }

    /**
     * 加盟商合同上传
     */



    @PostMapping("/importFranchiseeContract")
    @ResponseBody
    public BaseResult importFranchiseeContract(@RequestParam(value = "multipartFile") MultipartFile multipartFile,
                                               @RequestParam(value = "groupId")  Integer groupId,
                                               HttpServletRequest request) {
        File excelFile = FilePreFilter.transferToZipFile(multipartFile);
        Integer curUserId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        Locale locale = LocalStorageUtils.getStorageInfo().getLocale();

        if (curGroupId != null) {
            groupId = curGroupId;
        }

        //超级管理员 不让导入
        if (curUserId == null || groupId == null) {
            return BaseResult.noPrivilege();
        }

        String remoteIp = LogUtils.getRemoteIp(request);
        String platform = LogUtils.getPlatform(request);
        Locale finalLocale = locale;
        Integer finalGroupId = groupId;

        ThreadPoolTaskUtils.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    // 重新设置线程的本地变量
                    LocalStorageUtils.getStorageInfo().setLocale(locale);
                    BaseResult result = franchiseeContractService.importFranchiseeContract(excelFile,curUserId, finalGroupId, remoteIp, platform, finalLocale);
                } catch (Exception e) {
                    logger.error(LogUtil.getStackTraceInfo(e));
                    logger.info("Thread+importFranchiseeContract:" + e);
                }
            }
        });

        return BaseResult.success();
    }

    // 加盟商 模板自定义 保存


    /**
     * 自定义字段 保存
     * @param vo
     * @return
     */
    @PostMapping("/saveFranchiseesField")
    public BaseResult saveFranchiseesField(@RequestBody FranchiseesFieldSaveVo vo) {

        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if(curGroupId !=null){
            vo.setGroupId(curGroupId);
        }
        if(CollectionUtil.isNotEmpty(vo.getFranchiseesFieldVos()) && vo.getGroupId() !=null ){
            franchiseesRegistrationFieldService.saveFranchiseesField(vo,userId);
        }

        return BaseResult.success();
    }

    /**
     * 删除企业自定义模板
     * @param groupId
     * @return
     */

    @GetMapping("/deleteFranchiseesField")
    public BaseResult deleteFranchiseesField(@RequestParam("groupId") Integer groupId) {

        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if(curGroupId !=null){
            groupId = curGroupId;
        }
        franchiseesRegistrationFieldService.deleteFranchiseesFieldByGroupId(groupId);

        return BaseResult.success();
    }


    /**
     *  根据 logId 获取 日志详情
     */

    @GetMapping("/getFranchiseesRegistrationLogById")
    public BaseResult getFranchiseesRegistrationLogById(@RequestParam(value = "logId") Integer logId,
                                                        @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                                        @RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        Locale locale = LocalStorageUtils.getStorageInfo().getLocale();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        Map<String,Object> result = new HashMap<>();

        Page<FranchiseesRegistrationLog> page = new Page<>(pageNumber, pageSize);
        IPage<FranchiseesRegistrationLogVo> logVo = franchiseesRegistrationLogService.getFranchiseesRegistrationLogById(page,logId, locale);

        result.put("total", logVo.getTotal());
        result.put("data", logVo.getRecords());
        return BaseResult.success(result);
    }



}
